var features = false;
var pictures = [];
var related = [];
var t;
function getValue(id) {
    $("#" + id).children("div").children("p.alert-danger").text("");
    if ($("#" + id).find("li.active").length === 0) {
        $("#" + id).children("div").children("p.alert-danger").text("to pole jest wymagane");
        return false;
    }
    else {
        return li = $("#" + id).find("li.active").children("input").val();
    }
}
function addFeature(showhtml) {
    var id = false;
    if (showhtml === undefined || $.type(showhtml) === "object") {
        $("#features").html("");
        $("#noFeatures").addClass("hidden");
        id = $(this).children("input").val();
    }
    else {
        id = getValue("categories");
    }
    var data = {category: id};
    $.ajax({
        type: "POST",
        url: "/ajax/getCategoryFeatures",
        dataType: 'json',
        data: data,
        success: function (json) {
            if (json !== false)
            {
                features = json;
                if (showhtml === undefined || $.type(showhtml) === "object") {
                    $.each(json, function (index, value) {
                        console.log(json);
                        $("#features").append('<div class="form-group" id="group_' + value['CategoryFeatureID'] + '">');
                        $("#features").append('<label class="col-lg-4" >' + value['Name'] + '</label>');
                       $("#features").append('<select class="col-lg-4 input-sm" type="text" id="feature_' + value['CategoryFeatureID'] + '" name="feature_' + value['CategoryFeatureID'] + '">');
                        $.each(value["values"], function (key, val) {
                            $("#features").children("#feature_"+value['CategoryFeatureID']).append('<option value="'+val["FeatureValueID"]+'">'+val["Value"]+"</option>");
                        });
                    });
                }
            }
            else {
                features = false;
                $("#noFeatures").removeClass("hidden");
            }
        },
        error: function (data) {
            features = false;
            console.log(data.responseText);
        }
    });
}
function dodaj(event)
{
    related = [];
    var canAdd = true;
    t.rows().indexes().each(function (idx) {
        var d = t.row(idx).data();
        if (d[0] === event[0].name) {
            canAdd = false;
        }
    });
    $("#results").children(".list-group").html("");
    if (canAdd) {
        t.row.add([
            event[0].name, event[0].text, "<a class=\"usun\" href=\"#\">Usuń</a>"
        ]).draw();
    }
    t.rows().indexes().each(function (idx) {
        var d = t.row(idx).data();
        related.push(d);
        if (d[0] === event[0].name) {
            canAdd = false;
        }
    });
    ///  console.log(related);
}

$(document).ready(function () {
//    $("#editOpisPelny").Editor("opisPelny");
//    $("#editOpisKrotki").Editor("opisKrotki");
    t = $("#related2").DataTable({
        "paging": false,
        "info": false,
        "bFilter": false
    });
    $('#related2 tbody').on('click', '.usun', function () {
        related = [];
        t
                .row($(this).parents('tr'))
                .remove()
                .draw();
        t.rows().indexes().each(function (idx) {
            var d = t.row(idx).data();
            related.push(d);
            if (d[0] === event[0].name) {
                canAdd = false;
            }
        });
        // console.log(related);
    });
    $("#pictures").find("li").hover(function () {
        $(this).children("img").removeClass("hidden");
    }, function () {
        if (!$(this).hasClass("active"))
            $(this).children("img").addClass("hidden");
    });
    $("#pictures").find("li").click(function () {
        $("#pictures").find("li").children("img").addClass("hidden");
        $(this).children("img").removeClass("hidden");
    });
    var vat = $("#vatSelect").find("li.active").children("input").val();
    $("#vatSelect").find("li").click(function () {
        vat = $(this).children("a").text();
        vat = parseInt(vat);
    });
    $("#GrossPrice").next("button").click(function () {
        var price = $(this).prev("input").val();
        if (price !== "") {
            var newPrice = price / (1 + vat / 100);
            $("#NetPrice").val(newPrice.toFixed(2));
        }
    });
    $("#NetPrice").next("button").click(function () {
        var price = $(this).prev("input").val();
        if (price !== "") {
            var newPrice = price * (1 + vat / 100);
            $("#GrossPrice").val(newPrice.toFixed(2));
        }
    });


    $("ul.dropdown-menu").children("li").click(function () {
        $(this).parents("ul").children("li").removeClass("active");
        $(this).addClass("active");
        $(this).parent("ul").prev("button").html($(this).html() + "<span class=\"caret\">");
        $(this).parent("ul").parent("div").next("p").text("");
    });
    $("#formAddProduct").submit(function (event) {
        event.preventDefault();
        var name = $("#inputProductName").val();
        var productID = $("#productID").val();
        var edit = $("#edit").val();
        var fullDescritpion = $("#textarea_opisPelny").val();
        var shortDesription = $("#textarea_opisKrotki").val();
        var manufacturer = getValue("manufacturers");
        var category = getValue("categories");
        vat = getValue("vatSelect");
        var gross = $("#GrossPrice").val();
        var active = $("#active").val();
        var net = $("#NetPrice").val();
        var shopname = $("#shopname").val();
        pictures = [];
        $("input[name=picture]:checked").each(function () {
            pictures.push($(this).val());
        });
        var amount = $("#Amount").val();
        var mainPicture = $("input[name=picturemain]:checked").val();
        if (edit == 0)
            var url = "/" + shopname + "/ShopAdmin_Products/add";
        else
            url = "/" + shopname + "/ShopAdmin_Products/edit?ProductID=" + productID;
        if (!manufacturer || !category || !vat) {
            alert("wypełnij wszystkie pola");
        }
        else {
            if (features) {
                $.each(features, function (index, value) {
                    value["value"] = $("#feature_" + value['CategoryFeatureID']).val();
                    //$("#features").append(' <div class="form-group"><label class="col-lg-4" >' + value['Name'] + '</label><input class="col-lg-4 input-sm" type="text" name="feature_' + value['CategoryFeatureID'] + '"></div>');
                });
            }
            $.post(url,
                    {
                        name: name,
                        active: active,
                        fullDescritpion: fullDescritpion,
                        shortDesription: shortDesription,
                        manufacturer: manufacturer,
                        category: category,
                        vat: vat,
                        gross: gross,
                        net: net,
                        amount: amount,
                        pictures: pictures,
                        mainPicture: mainPicture,
                        features: features,
                        related: related
                    }).done(function (evt) {
                console.log(evt);
             //  window.location.href="/" + shopname + "/ShopAdmin_Products/";
            });
        }
    });
});